package com.rich.im.websocket;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rich.common.entity.Message;
import com.rich.im.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息发送
 * @author HanSama
 * @date 2021/8/16 11:02
 */

@Component
public class MessageHandler extends TextWebSocketHandler {

    @Autowired
    private MessageMapper messageMapper;

    private static final Map<Long,WebSocketSession> SESSIONS = new ConcurrentHashMap<>();

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     *建立连接后 向session添加登录人id信息
     * @author HanSama
     * @date 2021/8/13 16:30
     * @param session
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //获取请求路劲中的登陆人id
        Long uid = (Long) session.getAttributes().get("uid");
        //向session添加登录人id信息
        SESSIONS.put(uid,session);
    }

    /**
     * 断开链接后 删除session中数据
     * @author HanSama
     * @date 2021/8/13 17:30
     * @param session
     * @param status
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Long uid = (Long) session.getAttributes().get("uid");
        SESSIONS.remove(uid);
    }

    /**
     * 发送消息
     * @author HanSama
     * @date 2021/8/14 8:29
     * @param session
     * @param textMessage
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        //获取当前用户 id
        Long uid = (Long) session.getAttributes().get("uid");
        //将请求格式化为JSONMapper
        JsonNode jsonNode = MAPPER.readTree(textMessage.getPayload());
        //获取toid和消息内容
        Long toId = jsonNode.get("toId").asLong();
        String msg = jsonNode.get("msg").asText();
        //初始化消息
        Message message = new Message();
        message.setMsg(msg);
        message.setToId(toId);
        message.setFromId(uid);
        message.setSendDate(new Date());
        message.setStatus(1);
        //创建消息
        messageMapper.addMessage(message);


        // 判断to用户是否在线
        WebSocketSession toSession = SESSIONS.get(toId);
        if (toSession != null && toSession.isOpen()) {
            //具体格式需要和前端对接
            toSession.sendMessage(new
                    TextMessage(MAPPER.writeValueAsString(message.getMsg())));
            // 更新消息状态为已读
            messageMapper.updateMessageRead(message.getId(), 2,new Date());
        }

    }
}
